package com.myapp.web.struts2.interceptor;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AuthInterceptor extends AbstractInterceptor implements StrutsStatics{

	public final static String AUTH_PATH_KEY = "authPath";
	
	public final static String NO_AUTH = "no_auth";
	
	private static final long serialVersionUID = 5065120633434227796L;

	private String [] authPaths = null;
	
	private void resolvePath(String paths){
		System.out.println("*************resolvePath************************");
		if(paths == null){
			return ;
		}
		authPaths = paths.split(",");
	}
	
	public boolean checkLogin(){
		//HttpServletResponse response = ServletActionContext.getResponse();
	    HttpServletRequest request = ServletActionContext.getRequest();
	    String path = request.getContextPath();
	    for(String authPath : authPaths){
	    	if(path.startsWith(authPath)){
	    		return true;
	    	}
	    }
		return false;
	}
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		//String namespace = invocation.getProxy().getNamespace();
		if(authPaths == null){
			final ActionContext context = invocation.getInvocationContext();
	        ServletContext servletContext = (ServletContext) context.get(SERVLET_CONTEXT);
	        String paths = servletContext.getInitParameter(AUTH_PATH_KEY);	  
	        resolvePath(paths);
		}
        if(checkLogin()){
        	return NO_AUTH;
        }
        //servletContext.getInitParameterNames();
		return invocation.invoke();
	}

}
